package com.woniu.market_stall.intercepters;


import com.woniu.market_stall.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PermissionIntercepter implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));

        String path = request.getServletPath();
//        System.out.println(path);


        //跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if ("OPTIONS".equals(request.getMethod())){
            response.setStatus(HttpServletResponse.SC_OK);
            return true ;
        }

        //获取 token
        String token = request.getHeader("token");
        if (token == null) {
            //说明 请求头中没有token  说明没有登录
            response.getWriter().print("1");
        }else  {
            try {
                Claims claims = JwtUtil.parseToken(token);
                return true ;
            }catch (RuntimeException e){
                e.printStackTrace();
                response.getWriter().print("1");
            }
        }
        return false ;
    }
}

